using Gateway.Common.Enums;
using Gateway.Common.Extensions;
using Gateway.Common.Models;
using Gateway.Common.SqlSugar;
using SqlSugar;

namespace Gateway.SqlSugar;

public class SqlSugarDbContext
{
    public readonly SqlSugarScope Scope;

    public SqlSugarDbContext(string masterConnection, List<QueryConnectionModel> connections)
    {
        SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
            {
                DbType = DbType.MySql,
                ConnectionString = masterConnection,
                SlaveConnectionConfigs = connections.Select(p => new SlaveConnectionConfig()
                {
                    ConnectionString = p.Connection,
                    HitRate = (int)(p.Weight ?? 1)
                }).ToList(),
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute
            },
            db =>
            {
                db.Aop.OnLogExecuting = (sql, param) =>
                {
                    //打印sql 日志
                    var keyDic = new KeyValuePair<string, SugarParameter[]>(sql, param);
                    Console.WriteLine($"[sugar执行日志]{keyDic.ToJson()}");
                };
                db.QueryFilter.AddTableFilter<IDeleted>(it => it.Deleted == BooleanStatusEnum.No.Value);
                // db.QueryFilter.AddTableFilterIF(isAppendFilter:true ,typeof(IDeleted) ,it => it.Deleted == BooleanStatusEnum.No.Value);
                //查询过滤语句  过滤掉已删除的数据
                // db.QueryFilter.Add(new SqlFilterItem()
                //     {
                //         FilterValue = filterDb => { return new SqlFilterResult() { Sql = "  (Deleted='N' ) " }; },
                //         IsJoinQuery = false
                //     }).Add(new SqlFilterItem()
                //     {
                //         FilterValue = filterDb => { return new SqlFilterResult() { Sql = " m.Deleted='N' " }; },
                //         IsJoinQuery = true
                //     })
                //     ;
                // db.CurrentConnectionConfig.ConfigureExternalServices.SplitTableService = new SplitTableService();
            });
        Scope = sqlSugar;
    }
}